package com.ruoyi.web.controller.template;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.entity.templateentity.Template;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.config.Constant;
import com.ruoyi.web.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/template")
@CrossOrigin
public class TemplateController extends BaseController {

    @Autowired
    private TemplateService templateService;

    @Autowired
    private Constant constant;


    /**
     * 查询模板
     * @param template
     * @return
     */
    public TableDataInfo query(@RequestBody Template template){
        startPage();
        List<Template> list = templateService.query(template);
        return getDataTable(list);
    }

    /**
     * 新增模板
     * @param template
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Template template){
        int result = templateService.add(template);
        if (result==1)
            return AjaxResult.success();
        else
            return AjaxResult.error();
    }

    /**
     * 删除模板
     * @param id
     * @return
     */
    @GetMapping("delete/{id}")
    public AjaxResult delete(@PathVariable("id")String id){
        Template template = new Template();
        template.setId(id);
        List<Template> query = templateService.query(template);
        try {
            String fileName = query.get(0).getFileName();
            String resource = constant.getDOWNLOAD_PATH()+fileName;
            boolean b = FileUtils.deleteFile(resource);
            if (b) {
                int result = templateService.delete(id);
                if (result==1){
                    return AjaxResult.success();
                }else
                    return AjaxResult.error("删除失败！");
            }else {
                return AjaxResult.error("删除失败！");
            }
        }catch (Exception e){
            LogUtils.getBlock(e);
            e.printStackTrace();
            return AjaxResult.error();
        }

    }

}
